<?php
/**
 * User: lsx
 * Date: 2017/5/10
 * Time: 16:54
 * Progress:0%
 */

namespace logic\wechat\index;


use library\common\str;
use library\date;
use library\tencent\wechat\admin_wechat\SendTemplateMessage;
use model\Account;
use model\AccountBill;
use model\AccountPayment;
use model\AccountWechat;
use model\ShopConfig;
use model\ShopRegUserOrder;

use model\ShopUser;
use model\ShopUserCoupon;

use think\Config;
use think\Cookie;
use think\Db;

class LPay
{
    private $account;
    private $shopRegUserOrder;
    private $accountPayment;
    private $accountBill;
    private $accountWechat;
    private $shopConfig;


    private $shopUser;
    private $shopWatercard;

    public function __construct()
    {
        $this->account=new Account();
        $this->shopRegUserOrder=new ShopRegUserOrder();
        $this->accountPayment=new AccountPayment();
        $this->accountBill=new AccountBill();
        $this->accountWechat=new AccountWechat();
        $this->shopConfig=new ShopConfig();
        $this->shopUser=new ShopUser();

    }

    public function logic_index($type,$order_id){
        $data=array();
        $a_id=Cookie::get(Config::get('const.cookie_name_wechat'));
        switch ($type){
            case '0':
                $data=$this->shopRegUserOrder->where(['id'=>$order_id])->find();
                break;

        }
        $ac=$this->account->where(['id'=>$a_id])->find();
        if($ac->pay_password == null){
            $data->flag_pay_pwd=0;
        }else{
            $data->flag_pay_pwd=1;
        }
        $data->money=$ac->money;
        return  $data;
    }
//    微信支付
    public function logic_wechat_pay($param){
        //如果微信支付返回支付成功
        $wechat_pay_success=1;
        if($wechat_pay_success==1) {
            $a_id = Cookie::get(Config::get('const.cookie_name_wechat'));
            $ac = $this->account->where(['id' => $a_id])->find();
            //$param['type']:0:购买会员卡，1：购买vip会员卡,2:续费水卡
            switch ($param['type']){
                case '0':
                    return self::card_wechat_pay($ac->id,$param['order_sn']);
                    break;
                case '1':
                    return self::vipcard_wechat_pay($ac->id,$param['order_sn']);
                    break;
                case '2':
                    return self::renewals_watercard_pay($ac->id,$param['order_sn']);
                    break;
            }
        }
    }
//    余额支付
    public function logic_balance_pay($param){
        $a_id=Cookie::get(Config::get('const.cookie_name_wechat'));
        //验证支付密码是否正确
        $ac=$this->account->where(['id'=>$a_id])->find();
        if($ac->pay_password == null){
            return array(
                'success'=>false,
                'message'=>'未设置支付密码，请先设置支付密码。'
            );
        }
        if(md5($param['pay_password']) != $ac->pay_password){
            return array(
                'success'=>false,
                'message'=>'支付密码错误'
            );
        }
        //$param['type']:0:购买会员卡，1：购买vip会员卡,2:购买商品
        switch ($param['type']){
            case '0':
                return self::card_balance_pay($ac->id,$param['order_sn'],$ac->money);
                break;
            case '1':
                return self::vipcard_balance_pay($ac->id,$param['order_sn'],$ac->money);
                break;

        }
    }

    public function logic_take_coupon_save($param){
        $config_item=$this->shopConfig->find();
        $a_id=Cookie::get(Config::get('const.cookie_name_wechat'));
        $order=$this->shopRegUserOrder->where(['account_id'=>$a_id,'flag_pay'=>1])->find();
        if(!$order){
            return array(
                'success'=>false,
                'message'=>'你还没有购买会员，不能领取'
            );
        }
//        判断是否已领取
        if($order->flag_get_coupon == 1){
            return array(
                'success'=>false,
                'message'=>'已领取过优惠券'
            );
        };
        if($param['type']==0){//商品优惠券
            $data=array(
                'flag_get_coupon'=>1,
                'coupon_remark'=>'您已领取商品抵扣券券'
            );
            $res=$this->shopRegUserOrder->save($data,['id'=>$order['id']]);
            if(!$res){
                return array(
                    'success'=>false,
                    'message'=>'数据出错，请稍后再试'
                );
            }
            //优惠券领取表新增一条记录
            //todo 优惠券领取表新增一条记录

        }else if($param['type']==1){//vip优惠券
            $data=array(
                'flag_vip_coupon'=>1,
                'vip_coupon_deduction'=>$config_item->reg_user_vip_coupon_deduction,
                'flag_get_coupon'=>1,
                'coupon_remark'=>'您已领取vip会员卡优惠券'
            );
            $res=$this->shopRegUserOrder->save($data,['id'=>$order['id']]);
            if(!$res){
                return array(
                    'success'=>false,
                    'message'=>'数据出错，请稍后再试'
                );
            }
        }
        return array(
            'success'=>true,
            'message'=>'领取成功'
        );
    }
//    会员卡微信支付
    private function card_wechat_pay($account_id,$order_sn){
        $data=$this->shopRegUserOrder->where(['account_id'=>$account_id,'order_sn'=>$order_sn,'flag_pay'=>0])->find();
        if(!$data){
            return array(
                'success'=>false,
                'message'=>'数据出错0，请稍后再试'
            );
        }
        $order_pay=$data->order_pay;
        return self::card_pay_affairs($account_id,$order_sn,$order_pay);
    }

//    续费水卡微信支付


    //会员卡余额支付
    private function card_balance_pay($account_id,$order_sn,$account_money){
        $data=$this->shopRegUserOrder->where(['account_id'=>$account_id,'order_sn'=>$order_sn,'flag_pay'=>0])->find();
        if(!$data){
            return array(
                'success'=>false,
                'message'=>'数据出错0，请稍后再试'
            );
        }
        if($account_money < $data->order_pay){
            return array(
                'success'=>false,
                'code'=>-1,
                'message'=>'余额不足，请先充值'
            );
        }
        $ac_money=$account_money - $data->order_pay;
        $order_pay=$data->order_pay;
        return self::card_pay_affairs($account_id,$order_sn,$order_pay,$ac_money);
    }
    //vipcard会员卡余额支付
    private function vipcard_balance_pay($account_id,$order_sn,$account_money){


    }
    //商品余额支付
    private function goods_balance_pay($account_id,$order_sn,$account_money){

    }


    //购买会员卡事务
    private function card_pay_affairs($a_id,$order_sn,$order_pay,$ac_money=null){
        Db::startTrans();
        //账户余额扣除
        if($ac_money){
            $res1=$this->account->save(['money'=>$ac_money],['id'=>$a_id]);
            if(!$res1){
                Db::rollback();
                return array(
                    'success'=>false,
                    'message'=>'数据出错1，请稍后再试'
                );
            }
        }

        //生成支付记录
        $data2=array(
            'account_id'=>$a_id,
            'pay_type'=>5,
            'pay_no'=>$order_sn,
            'pay_time'=>time(),
            'flag_pay'=>1,
            'flag_lock'=>1,
            'remark'=>'19.8元购买会员',
            'add_time'=>time()

        );

        $res2=$this->accountPayment->insertGetId($data2);
        if(!$res2){
            Db::rollback();
            return array(
                'success'=>false,
                'message'=>'数据出错2，请稍后再试'
            );
        }
        // 插入钱帐记录

        $data3=array(
            ['account_id'=>$a_id,'money'=>$order_pay,'remark'=>'19.8元购买会员-充值'],
            ['account_id'=>$a_id,'money'=>0-$order_pay,'remark'=>'19.8元购买会员-消费'],
        );

        $res3=$this->accountBill->saveAll($data3);
        if(!$res3){
            Db::rollback();
            return array(
                'success'=>false,
                'message'=>'数据出错3，请稍后再试'
            );
        }

        //更改订单支付状态
        $data4=array(
            'gift_code'=>str::randomNum(9),
            'flag_pay'=>1,
            'payment_id'=>$res2,
            'pay_time'=>time()
        );
        $res4=$this->shopRegUserOrder->save($data4,['account_id'=>$a_id,'order_sn'=>$order_sn]);
        if(!$res4){
            Db::rollback();
            return array(
                'success'=>false,
                'message'=>'数据出错4，请稍后再试'
            );
        }
        Db::commit();
        //事务成功，调用微信模板消息接口,返回数据
        //调用微信模板消息接口
//        $oauth=$this->accountWechat->where(['account_id'=>$a_id])->find();
//        $openid=$oauth['openid'];
//        $data=array(
//            'touser'=>$openid,
//            'keyword1'=>$order_sn,
//            'keyword2'=>"支付成功",
//            'keyword3'=>date('Y-m-d',time()),
//            'keyword4'=>"巴马和泉",
//            'keyword5'=>$order_pay.'元'
//        );
//        SendTemplateMessage::send_message("OPENTM204987032",$data);
        //返现给上级
        self::cash_back($a_id,$order_sn,$type=0);
        //返回数据
        return array(
            'success'=>true,
            'message'=>'支付成功',
            'url'=>url('Pay/take_coupon')
        );
    }
    //购买vip会员卡事务
    private function vipcard_pay_affairs($a_id,$order_sn,$order_pay,$ac_money=null){
        Db::startTrans();
        //账户余额扣除
        if($ac_money){
            $res1=$this->account->save(['money'=>$ac_money],['id'=>$a_id]);
            if(!$res1){
                Db::rollback();
                return array(
                    'success'=>false,
                    'message'=>'数据出错1，请稍后再试'
                );
            }
        }
        //生成支付记录
        $data2=array(
            'account_id'=>$a_id,
            'pay_type'=>5,
            'pay_no'=>$order_sn,
            'pay_time'=>time(),
            'flag_pay'=>1,
            'flag_lock'=>1,
            'remark'=>'购买vip会员卡',
            'add_time'=>time()

        );

        $res2=$this->accountPayment->insertGetId($data2);

        if(!$res2){
            Db::rollback();
            return array(
                'success'=>false,
                'message'=>'数据出错2，请稍后再试'
            );
        }
        // 插入钱帐记录

        $data3=array(
            ['account_id'=>$a_id,'money'=>$order_pay,'remark'=>'购买vip会员卡-充值'],
            ['account_id'=>$a_id,'money'=>0-$order_pay,'remark'=>'购买vip会员卡-消费'],
        );

        $res3=$this->accountBill->saveAll($data3);
        if(!$res3){
            Db::rollback();
            return array(
                'success'=>false,
                'message'=>'数据出错3，请稍后再试'
            );
        }



        //添加shop_user一条记录
        $data5=array(
            'account_id'=>$a_id,
            'group_id'=>2,
            'card_sn'=>"00000000"
        );
        $res5=$this->shopUser->save($data5);

        if(!$res5){
            Db::rollback();
            return array(
                'success'=>false,
                'message'=>'数据出错5，请稍后再试'
            );
        }




        Db::commit();
        //事务成功，调用微信模板消息接口,返回数据
        //调用微信模板消息接口
//        $oauth=$this->accountWechat->where(['account_id'=>$a_id])->find();
//        $openid=$oauth['openid'];
//        $data=array(
//            'touser'=>$openid,
//            'keyword1'=>$order_sn,
//            'keyword2'=>"支付成功",
//            'keyword3'=>date('Y-m-d',time()),
//            'keyword4'=>"巴马和泉",
//            'keyword5'=>$order_pay.'元'
//        );
//        SendTemplateMessage::send_message("OPENTM204987032",$data);
        //返现给上级
        self::cash_back($a_id,$order_sn,$type=1);
        //返回数据
        return array(
            'success'=>true,
            'message'=>'支付成功',
            'url'=>url('Index/index')
        );
    }
    //续费水卡事务
    private function renewals_watercard_pay_affairs($user_card_id,$a_id,$order_sn,$order_pay,$ac_money=null){
        Db::startTrans();
        //账户余额扣除
        if($ac_money){
            $res1=$this->account->save(['money'=>$ac_money],['id'=>$a_id]);
            if(!$res1){
                Db::rollback();
                return array(
                    'success'=>false,
                    'message'=>'数据出错1，请稍后再试'
                );
            }
        }
        //生成支付记录
        $data2=array(
            'account_id'=>$a_id,
            'pay_type'=>5,
            'pay_no'=>$order_sn,
            'pay_time'=>time(),
            'flag_pay'=>1,
            'flag_lock'=>1,
            'remark'=>'续费水卡',
            'add_time'=>time()

        );

        $res2=$this->accountPayment->insertGetId($data2);

        if(!$res2){
            Db::rollback();
            return array(
                'success'=>false,
                'message'=>'数据出错2，请稍后再试'
            );
        }
        // 插入钱帐记录

        $data3=array(
            ['account_id'=>$a_id,'money'=>$order_pay,'remark'=>'续费水卡-充值'],
            ['account_id'=>$a_id,'money'=>0-$order_pay,'remark'=>'续费水卡-消费'],
        );

        $res3=$this->accountBill->saveAll($data3);
        if(!$res3){
            Db::rollback();
            return array(
                'success'=>false,
                'message'=>'数据出错3，请稍后再试'
            );
        }




        Db::commit();
        //事务成功，调用微信模板消息接口,返回数据
        //调用微信模板消息接口
//        $oauth=$this->accountWechat->where(['account_id'=>$a_id])->find();
//        $openid=$oauth['openid'];
//        $data=array(
//            'touser'=>$openid,
//            'keyword1'=>$order_sn,
//            'keyword2'=>"支付成功",
//            'keyword3'=>date('Y-m-d',time()),
//            'keyword4'=>"巴马和泉",
//            'keyword5'=>$order_pay.'元'
//        );
//        SendTemplateMessage::send_message("OPENTM204987032",$data);
        //返现给上级
//        self::cash_back($a_id,$order_sn,$type=1);
        //返回数据
        return array(
            'success'=>true,
            'message'=>'支付成功',
            'url'=>url('User/wc')
        );
    }

    private function cash_back($account_id,$order_sn,$type){
    $config=$this->shopConfig->find();

    $parent_id=$this->account->where(['id'=>$account_id])->value('parent_id');

    if($parent_id){//有上级，返现事务
        $cash=0;
        switch ($type){
            case 0:
                $cash=$config->commission_group1;
                break;
            case 1:
                //todo
//            if("股东会员"){
//                $cash=$config->commission_group3;
//            }else if("vip会员"){
//                $cash=$config->commission_group2;
//            }
                $cash=$config->commission_group2;
                break;
        }

        if($cash>0){
            //bill表增加两条记录----account表余额增加2元
            Db::startTrans();
            $data1= ['account_id'=>$parent_id,'money'=>$cash,'remark'=>'下级购买会员返现-充值'];
            $res1=$this->accountBill->save($data1);
            if(!$res1){
                Db::rollback();
                return array(
                    'success'=>false,
                    'message'=>'数据出错，请稍后再试'
                );
            };
            $res2=$this->account->where(['id'=>$parent_id])->setInc('money', $cash);
            if(!$res2){
                Db::rollback();
                return array(
                    'success'=>false,
                    'message'=>'数据出错，请稍后再试'
                );
            };
            Db::commit();
//            $oauth=$this->accountWechat->where(['account_id'=>$parent_id])->find();
//            $openid=$oauth['openid'];
//            $data=array(
//                'touser'=>$openid,
//                'order'=>$order_sn,
//                'money'=>$cash."元",
//            );
//            SendTemplateMessage::send_message("TM00211",$data);
        }
    }
}


}